package com.spring.web.action;

import java.io.PrintWriter;
import java.util.Enumeration;
import java.util.HashMap;
import java.util.Map;

import javax.servlet.http.Cookie;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;

import net.sf.json.JSONArray;
import net.sf.json.JSONObject;

import org.apache.commons.beanutils.BeanUtils;
import org.apache.commons.beanutils.PropertyUtils;
import org.apache.commons.lang.StringUtils;
import org.apache.commons.logging.Log;
import org.apache.commons.logging.LogFactory;
import org.jsoup.Jsoup;
import org.springframework.web.context.request.RequestContextHolder;
import org.springframework.web.context.request.ServletRequestAttributes;

import com.spring.bean.page.Page;
import com.spring.utils.Constants;

public class Action {
	
	private static final Log log = LogFactory.getLog(Action.class);
	
	/** get request */ 
	public HttpServletRequest getRequest(){
		return ((ServletRequestAttributes) RequestContextHolder.getRequestAttributes()).getRequest();
	}
	
	/** get session */
	public HttpSession getSession(){
		return getRequest().getSession();
	}
	
	/** _params to form */
	@SuppressWarnings({ "unchecked", "rawtypes" })
	public <T> T paramsToForm(Class<T> formClass){
		T formBean = null;
			try{
			HttpServletRequest request = getRequest();
			Enumeration<String> paramNames = request.getParameterNames();
			// 实例化formBean对象
			formBean = formClass.newInstance();
			String paramName = null;
			String[] values = null;
			String value = null;
			
			// 进行遍历赋值
			while(paramNames.hasMoreElements()){
				paramName = paramNames.nextElement();
				// 当传来的参数是数组时（页面参数要以[]结尾，才可被识别为数组），进行下面处理
				if(paramName.endsWith("[]")){
					values = request.getParameterValues(paramName);
					String s = paramName.replaceAll("\\[\\]", "");
					// commons工具类,无转换参数类型的功能,所以在form接受时一律为String类型，在使用时进行转换
					PropertyUtils.setProperty(formBean, s, values);
					// 结束本次循环，直接执行下一次循环
					continue;
				}
				
				// 不为数组时，不空时，直接为对象赋值
				value = request.getParameter(paramName);
				if(!StringUtils.isBlank(value)){
					value = filterUserInputContent(value);
					// commons工具类,具有转换参数类型的功能
					BeanUtils.setProperty(formBean, paramName, value);
					// 结束本次循环，直接执行下一次循环
					continue;
				}
				
				// 当传过来为空串，或为null时，则对String类型的作特殊处理，来适应自动生成sql
				// 所以要使用Form中的自定义的方法对其是否为空进行判断
				Class c = PropertyUtils.getPropertyType(formBean, paramName);
				if(c != String.class){
					PropertyUtils.setProperty(formBean, paramName, null);
				} else {
					PropertyUtils.setProperty(formBean, paramName, Constants.WEB_KEY_NULL);
				}
			}
		} catch(Exception e){
			e.printStackTrace();
		}
		return formBean;
	}
	
	/**
	 * 对用户输入内容进行过滤（过滤危险代码）
	 * @param html
	 * @return
	 */
	public static String filterUserInputContent(String html) {
		if(StringUtils.isBlank(html)) return "";
		return Jsoup.clean(html, Constants.USER_CONTENT_FILTER_BASIC);
	}
	
	public Page getPage(){
		String currentpage = getRequest().getParameter("currentpage");
		if(StringUtils.isBlank(currentpage) || "0".equals(currentpage)){
			currentpage = "1";
		}
		return new Page(Integer.parseInt(currentpage), Constants.MAX_RESULT);
	}
	
	/**
	 * 是否刷新重复提交
	 * @return 
	 * 	true 是
	 * 	false 否, 并清空提交标志
	 */
	public boolean isReSubmit(){
		if(getSession().getAttribute(Constants.FORM_SUBMIT_SIGN) == null){
			return true;
		}
		getSession().removeAttribute(Constants.FORM_SUBMIT_SIGN);
		return false;
	} 
	
	/* ----------------------------- _json -------------------------------------- */
	/**
	 * sendJson
	 */
	protected void sendJson(String content, HttpServletResponse response) {
		try{
			if(StringUtils.isBlank(content))
				return;
			response.setContentType("text/html;charset=UTF-8");			
			PrintWriter writer = response.getWriter();
			writer.write(content);
			writer.flush();
			log.debug(content);
		}catch (Exception e) {
			log.error(e);
		}
	}
	public void outputJsonObject(Object obj, HttpServletResponse response) {
		JSONObject o = JSONObject.fromObject(obj);
		try {
			response.setContentType("text/plain;charset=UTF-8");
			PrintWriter writer = response.getWriter();
			writer.write(o.toString());
			writer.flush();
		} catch (Exception e) {
			log.error(e.getMessage(), e);
		}
	}
	public void outputJsonArray(Object obj, HttpServletResponse response) {
		JSONArray arr = JSONArray.fromObject(obj);
		try {
			response.setContentType("text/plain;charset=UTF-8");
			PrintWriter writer = response.getWriter();
			writer.write(arr.toString());
			writer.flush();
		} catch (Exception e) {
			log.error(e.getMessage(), e);
		}
	}
	
	/* ----------------------------- Cookie ---------------------------------- */
	
	/** addCookie */
	public static void addCookie(HttpServletResponse response,String name,String value,int maxAge){
	    Cookie cookie = new Cookie(name,value);
	    cookie.setPath("/");
	    if(maxAge > 0)  
	    	cookie.setMaxAge(maxAge);
	    response.addCookie(cookie);
	}
	
	/** getCookieByName */
	public static Cookie getCookieByName(HttpServletRequest request, String name) {
		Map<String, Cookie> map = getCookieMap(request);
		if(map.containsKey(name)){
			return map.get(name);
		}
		return null;
	}
	
	/** getCookieMap */
	public static Map<String, Cookie> getCookieMap(HttpServletRequest request) {
		Map<String, Cookie> cookieMap = new HashMap<String, Cookie>();
		Cookie[] cookies = request.getCookies();
		for(int i=0; i<cookies.length; i++){
			cookieMap.put(cookies[i].getName(), cookies[i]);
		}
		return cookieMap;
	}
	
	
}
